package com.ccl.iot.privates;import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class UID {
	public final static long KINVALID_UID = 1;
	
	private static Object gSyncLock = new Object();
	
	private static ArrayList<WeakReference<Object>> gObjectList = null;
	private static ArrayList<Long> gIDList = null;
	
	public static long GetUID(Object aObject){
		if (aObject != null){
			WeakReference<Object> tReference;
			
			synchronized(gSyncLock){
				if (gObjectList == null || gIDList == null){
					gObjectList = new ArrayList<WeakReference<Object>>();
					gIDList = new ArrayList<Long>();
				}else{
					int tSize = gObjectList.size();
					
					if (gIDList != null && gIDList.size() == tSize){
						for (int i = gObjectList.size() - 1; i >= 0; i--){
							tReference = gObjectList.get(i);
							
							if (tReference != null){
								Object tObject = tReference.get();
								
								if (tObject != null){
									if (tObject == aObject){
										return gIDList.get(i);
									}
								}else{
									gObjectList.remove(i);
									gIDList.remove(i);
								}
							}else{
								gObjectList.remove(i);
								gIDList.remove(i);
							}
						}
					}else{
						if (tSize > 0){
							gObjectList.clear();
						}
						
						if (gIDList != null && gIDList.size() > 0){
							gIDList.clear();
						}
					}
				}
				
				if (gObjectList.add(tReference = new WeakReference<Object>(aObject))){
					long tID = System.currentTimeMillis();
					
					while ((gIDList.contains(tID))){
						tID++;
					}
					
					if (gIDList.add(tID)){
						return tID;
					}else{
						gObjectList.remove(tReference);
					}
				}
			}
		}
		
		return KINVALID_UID;
	}
}
